//
//  WBREfreshControl.swift
//  Weibo
//
//  Created by 明丽 on 16/1/22.
//  Copyright © 2016年 明丽. All rights reserved.
//

import UIKit
private let RefreshHeight: CGFloat = 60
//自定义枚举 各个阶段的状态
enum WBRefreshStatue: Int {
    case Normal = 1     //普通状态
    case Pulling = 2    //下拉到等待刷新状态
    case Refreshing = 3 //正在刷新状态
}

class WBREfreshControl: UIControl {
    //MARK: 定义外部变量
    //定义属性 记录上一次的刷新状态
    var oldStatue: WBRefreshStatue = .Normal

    var statue: WBRefreshStatue = .Normal{
        didSet {
        //根据状态修改ui
            switch statue {
            case .Normal:
                titLable.text = "下拉起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                //显示箭头
                arrowIcon.hidden = false
                //关闭动画
                indicationView.stopAnimating()
                if oldStatue == .Refreshing{
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scollView!.contentInset
                        //顶部加 刷新控件的高度
                        inset.top -= RefreshHeight
                        //修改
                        self.scollView?.contentInset = inset
                    })

                
                }
            case .Pulling:
                titLable.text = "准备起飞"
                //改变箭头方向
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })

            case .Refreshing:
                titLable.text = "正在起飞"
                //隐藏箭头
                arrowIcon.hidden = true
                //让小菊花转
                indicationView.startAnimating()
                 //模拟系统时间类型
                sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //修改scrollView的contentInset
                    var inset = self.scollView!.contentInset
                    //顶部加 刷新控件的高度
                    inset.top += RefreshHeight
                    //修改
                    self.scollView?.contentInset = inset
                })

                
            }
        //记录上一次刷新 状态
            oldStatue = statue
        
        }
    
    }
//uicontrol有处发时间的机制,继承uiview
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y:-RefreshHeight, width: KWidth, height: RefreshHeight)
        super.init(frame: rect)
        backgroundColor = UIColor.yellowColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
       // print("我是监听")
        //获取临界值
        let conaditionValue = -((self.scollView?.contentInset.top ?? 0)+RefreshHeight)
        //获取偏移量
        let offsetY = self.scollView?.contentOffset.y ?? 0
        //刷新状态超出临界值并且松手
        if scollView!.dragging{
        //拖动状态
            if statue == .Normal && conaditionValue > offsetY {
            
            print("等待刷新")
            statue = .Pulling
            } else if statue == .Pulling && conaditionValue < offsetY{
            
            print("普通状态")
                statue = .Normal
            }
        
        }else {
            if statue == .Pulling{
             print("正在刷新")
            statue = .Refreshing
            }
        }
        
        
    }
    //修改终止刷新操作
    func endrefreshing() {
        //延时 0.3秒
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.3))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let myFather = newSuperview as? UIScrollView {
          self.scollView = myFather
            scollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    //移除监听
    deinit {
    
    
    scollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    private var scollView: UIScrollView?
    
    
    //设置视图
  private func setupUI(){
    addSubview(titLable)
    addSubview(arrowIcon)
    addSubview(indicationView)
    //设置约束
    titLable.snp_makeConstraints { (make) -> Void in
        make.centerX.equalTo(self.snp_centerX).offset(15)
        make.centerY.equalTo(self.snp_centerY)
    }
    
    arrowIcon.snp_makeConstraints { (make) -> Void in
        make.right.equalTo(titLable.snp_left).offset(5)
        make.centerY.equalTo(titLable.snp_centerY)
    }
    indicationView.snp_makeConstraints { (make) -> Void in
        make.center.equalTo(arrowIcon.snp_center)
    }
    
    
    }
    
    //懒加视图
    private lazy var titLable : UILabel =  UILabel(title: "下拉刷新", fontSize: 14, color: UIColor.blueColor())
    //箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named:"tableview_pull_refresh"))
    //小菊花
    private lazy var indicationView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)

    
    
}
